<?php

namespace App\Http\Controllers;

use App\Exceptions\CourseChangeException;
use App\Internals\CourseInternal;
use App\Models\UserCourse;
use App\Models\UserLesson;
use App\Models\UserStatus;
use FoxLib\Services\UrlParamsService;
use Illuminate\Support\Facades\DB;

class CourseController extends Controller
{
    /*
     * @api get /study-api/courses/current 获取用户当前的课程
     * @version 0.0.1
     * @group web
     *
     * @response 200 正常结果 {
     *  "code":0,
     *  "msg":"",
     *  "data":{
     *  }
     * }
     */
    public function current()
    {
        $this->validate($this->request, [
            "page" => "integer|min:1",
            "pageSize" => "integer|max:100|min:5"
        ]);
        $page = intval($this->request->input("page", 1));
        $pageSize = intval($this->request->input("pageSize", 15));
        /** @var UserCourse $courseObj */
        $courseObj = UserCourse::getCurrent($this->userId);
        $total = 0;
        $isEnd = 0;
        $items = [];
        $course = [];
        if ($courseObj) {
            // is_end=1表示课时lesson推送已结束，这时才检查是否全部课时已学习完成,如是则is_end设为2
            if ($courseObj->getIsEnd() == UserCourse::IS_END['push']
                && UserLesson::isFinishedUserCourseLessons($this->userId, $courseObj->getCourseId())) {
                $score = UserLesson::ofUserCourseOfficialLessons($this->userId, $courseObj->getCourseId())->avg('score');
                $star = ceil($score / 100);
                $isEnd = 1;
                $courseObj->setIsEnd(UserCourse::IS_END['learn']);
                $courseObj->setEndTime($this->nowTimestamp());
                $courseObj->setScore($score);
                $courseObj->setStar($star);
                $courseObj->save();
            }
            $total = UserLesson::ofUserCourseEnableLessons($this->userId, $courseObj->getCourseId(), $this->nowTimestamp())->count();
            // 如果还没有体验课，赠送体验课
            if (!$total) {
                $firstLesson = CourseInternal::getLevelFirstLesson($courseObj->getLevel());
                if ($firstLesson) {
                    $lessonObj = new UserLesson();
                    $lessonObj->setUserId($this->userId);
                    $lessonObj->setLessonId($firstLesson['firstLessonId']);
                    $lessonObj->setCourseId($courseObj->getCourseId());
                    $lessonObj->setSequence($firstLesson['sequence']);
                    $lessonObj->setWordCount($firstLesson['wordCount']);
                    $lessonObj->setEnableTime($this->nowTimestamp());
                    $lessonObj->setKnowledgeCount($firstLesson['knowledgeCount']);
                    $lessonObj->setEssenceQaCount($firstLesson['essenceQaCount']);
                    $lessonObj->setGameTestCount($firstLesson['gameTestCount']);
                    $lessonObj->setGameWordCount($firstLesson['gameWordCount']);
                    $lessonObj->save();
                    $total = 1;
                }
            }
            if ($total) {
                $lessonsObj = UserLesson::ofUserCourseEnableLessons($this->userId, $courseObj->getCourseId(), $this->nowTimestamp())
                    ->orderBy('id', 'desc')->forPage($page, $pageSize)->get();
                $lessonIds = [];
                /** @var UserLesson $lessonObj */
                foreach ($lessonsObj as $lessonObj) {
                    $lessonIds[] = $lessonObj->getLessonId();
                }
                $lessonsInfo = CourseInternal::getLessons($lessonIds);
                foreach ($lessonsObj as $lessonObj) {
                    $item = $lessonsInfo[$lessonObj->getLessonId()];
                    $item['status'] = $lessonObj->getStudyStatus();
                    $item['star'] = $lessonObj->getStar();
                    $item['sequence'] = $lessonObj->getSequence();
                    $items[] = $item;
                }
            }
            if ($isEnd) {
                $nextCourseInfo = UserCourse::getNextCourse($this->userId, $courseObj->getLevel());
                $course = [
                    'currentLevel' => $courseObj->getLevel(),
                    'star' => $courseObj->getStar(),
                    'nextLevel' => $nextCourseInfo['nextLevel'],
                    'isBuy' => $nextCourseInfo['isBuy'],
                    'nextCourseId' => $nextCourseInfo['nextCourseId'],
                    'dateCount' => $courseObj->getStudyDateCount(),
                    'wordCount' => $courseObj->getWordCount(),
                    'refer' => UrlParamsService::encode(['userId' => $this->userId, 'courseId' => $courseObj->getCourseId()])
                ];

            } else {
                $course = [
                    'currentLevel' => $courseObj->getLevel(),
                ];
            }
        }
        return $this->sendSuccessJson(['total'=>$total, 'items'=>$items, 'isEnd' => $isEnd, 'course' => $course]);
    }


    /*
     * @api get /study-api/courses 学习课程列表
     * @version 0.0.1
     * @group web
     *
     * @response 200 正常结果 {
     *  "code":0,
     *  "msg":"",
     *  "data":{
     *  }
     * }
     */
    public function getList()
    {
        $coursesInfo = CourseInternal::getCourses();
        foreach ($coursesInfo as $k  => &$item) {
            /** @var UserCourse $userCourseObj */
            $userCourseObj = UserCourse::ofUserBuyCourse($this->userId, $item['id'])->first();
            if ($userCourseObj) {
                $item['isCurrent'] = $userCourseObj->getIsCurrent();
                $item['studiedLessonCount'] = $userCourseObj->getLessonCount();
                $item['isBuy'] = 1;
            } else {
                $item['isCurrent'] = 0;
                $item['studiedLessonCount'] = 0;
                $item['isBuy'] = 0;
            }
        }
        return $this->sendSuccessJson($coursesInfo);
    }

    /*
     * @api get /study-api/courses/level/{level} 学习课程列表
     * @version 0.0.1
     * @group web
     *
     * @response 200 正常结果 {
     *  "code":0,
     *  "msg":"",
     *  "data":{
     *  }
     * }
     */
    public function getByLevel($level)
    {
        $result = [
            'isBuy' => UserCourse::ofUserBuyLevel($this->userId, $level)->exists()
        ];
        return $this->sendSuccessJson($result);
    }

    /*
     * @api put /study-api/courses/current 更新正在学习的课程
     * @version 0.0.1
     * @group web
     *
     * @param body int level 等级
     *
     * @response 200 正常结果 {
     *  "code":0,
     *  "msg":"",
     *  "data":{}
     * }
     */
    public function updateCurrentCourse()
    {
        // 体验时，不更新
        $this->validate($this->request, [
            'courseId' => 'required|integer',
            'level' => 'required|integer'
        ]);
        $courseId = $this->request->input('courseId');
        $level = $this->request->input('level');
        try {
            if ($courseId) {
                $userCourseObj = UserCourse::ofUserBuyCourse($this->userId, $courseId)->first();
            } else {
                $userCourseObj = UserCourse::ofUserBuyLevel($this->userId, $level)->first();
            }

            if ($userCourseObj) {
                DB::beginTransaction();
                UserCourse::where('user_id', $this->userId)->where('is_current', UserCourse::IS_TRUE)->update(['is_current' => UserCourse::IS_FALSE]);
                /** @var UserCourse $userCourseObj */
                $userCourseObj->setIsCurrent(UserCourse::IS_TRUE);
                if (!$userCourseObj->getStartTime()) {
                    $userCourseObj->setStartTime($this->nowTimestamp());
                }
                $userCourseObj->save();
                /** @var UserStatus $userStatusObj */
                $userStatusObj = UserStatus::where('user_id', $this->userId)->first();
                $userStatusObj->setCurrentLevel($userCourseObj->getLevel());
                $userStatusObj->save();
                DB::commit();
            }
        } catch (\Exception $e) {
            DB::rollBack();
            throw new CourseChangeException();
        }
        return $this->sendSuccessJson();
    }
}
